package com.cskaoyan.typehandler;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * @author: yudefu
 * @date 2021年06月06日  17:47
 * @description: 另一个String变成String[] 的类
 */

//@MappedTypes(String[].class)
//@MappedJdbcTypes(JdbcType.VARCHAR)
public class AnotherStringArrayTypeHandler implements TypeHandler<String[]> {


    private static final String splitCharset = ",";

    //输入映射 String[] → String
    //index:输入映射过程中，预编译 占位符的顺序
    @Override
    public void setParameter(PreparedStatement ps, int index, String[] parameter, JdbcType jdbcType) throws SQLException {

        String value = arrayToString(parameter);

        ps.setString(index,value);
    }

    //输出映射，结果的封装 String → String[]
    @Override
    public String[] getResult(ResultSet rs, String columnName) throws SQLException {

        String result = rs.getString(columnName);

        return stringToArray(result);
    }

    @Override
    public String[] getResult(ResultSet rs, int columnIndex) throws SQLException {

        String result = rs.getString(columnIndex);
        return stringToArray(result);
    }

    @Override
    public String[] getResult(CallableStatement cs, int columnIndex) throws SQLException {

        String result = cs.getString(columnIndex);

        return stringToArray(result);
    }


    private static String arrayToString(String[] array) {
        StringBuilder res = new StringBuilder();
        if (array != null && array.length > 0) {
            for (String s : array) {
                res.append(splitCharset).append(s);
            }
            res.append(splitCharset);
        }
        return res.length() > 0 ? res.toString() : null;
    }

    private static String[] stringToArray(String str) {

        ArrayList<String> list = new ArrayList<>();
        if (str != null) {
            String[] array = str.split(splitCharset);
            if (array.length > 0) {
                for (String s : array) {
                    if (s != null && s.length() > 0) {
                        list.add(s);
                    }
                }
            }
        }
        return list.toArray(new String[0]);
    }
}
